package com.renbang.utils;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
/**
 * 
 * @description 获得一个城市的天气信息
 * @author user
 * @date 2017年5月4日
 */
public class WebxmlUtils {

	public static void main(String[] args) throws Exception {
		System.out.println(getMobileCodeInfo("13055147705"));
	}
	/**
	 * 
	 * @Description:获取天气信息
	 * @author:user
	 * @param city
	 * @return String
	 * @date 2017年5月4日
	 */
	public static String getWeather(String city) throws Exception{
		String urlStr = "http://ws.webxml.com.cn/WebServices/WeatherWS.asmx/getWeather?theUserID=&theCityCode="+city;
		return getInfo(urlStr);
	}
	/**
	 * 
	 * @Description:获取号码信息
	 * @author:user
	 * @param mobileCode
	 * @return String
	 * @date 2017年5月4日
	 */
	public static String getMobileCodeInfo(String mobileCode) throws Exception{
		String urlStr = "http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo?userID=&mobileCode="+mobileCode;
		return getInfo(urlStr);
	}
	/**
	 * 
	 * @Description:根据链接获取xml并且解析
	 * @author:user
	 * @param WebxmlUtils.java
	 * @return String
	 * @date 2017年5月4日
	 */
	private static String getInfo(String urlStr) throws Exception {
		URL url = new URL(urlStr);
		
		URLConnection uc = url.openConnection();
		InputStream br = uc.getInputStream();
		Document doc;
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		dbf.setNamespaceAware(true);
		DocumentBuilder db = dbf.newDocumentBuilder();
		doc = db.parse(br);// 得到doc文档
		NodeList nl = doc.getElementsByTagName("string");
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < nl.getLength(); i++) {
			Node n = nl.item(i);
			String weather = n.getFirstChild().getNodeValue();
			if(weather.contains("gif")){
				HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
				String projectPath = request.getContextPath();
				System.out.println(projectPath);
				weather="<img width='50px' height='50px' src='"+projectPath+"/resource/css/weather/"+weather+"' >";
			}
			sb.append("<p>"+weather + "</p>");
		}
		return sb.toString();
	}
	
	
}
